package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {


    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
            //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件的输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();

            //添加随机id值，为了防止上传同样的文件被覆盖
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //把文件按照日期分类
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //日期和file拼接
            fileName = datePath+"/"+fileName;

            //调用oss方法实现上传
            //第一个参数 bucket名称
            //第二个参数：上传oss文件路径和文件名称
            //第三个参数，上传文件的输入流
            ossClient.putObject(bucketName,fileName,inputStream);

            //关闭OSS
            ossClient.shutdown();

            //返回上传之后的文件路径
            //需要拼接阿里云oss文件的路径
            //https://edu-2020-10.oss-cn-beijing.aliyuncs.com/1.PNG

            String url = "https://" +bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
